package com.umbrella.worker.web.controller;


import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.umbrella.worker.util.PageBeanUtil;
import com.umbrella.worker.dto.MemberCouponDO;
import com.umbrella.worker.dto.MembersDO;
import com.umbrella.worker.dto.TaskDO;
import com.umbrella.worker.dto.ContactDO;
import com.umbrella.worker.dto.OrderDO;
import com.umbrella.worker.dto.OrderDetailDO;
import com.umbrella.worker.query.OrderQuery;
import com.umbrella.worker.result.ResultDO;
import com.umbrella.worker.result.ResultSupport;
import com.umbrella.worker.service.IMemberService;
import com.umbrella.worker.service.IOrderService;



@Controller
@RequestMapping(value = "/order")
public class OrderController extends BaseController{
	
	@Autowired
	private IOrderService orderService;
		
	@Autowired
	private IMemberService memberService;
	
	
	@RequestMapping(value = "/getOrder.html", method = RequestMethod.GET)
	public ModelAndView getOrder(ModelAndView mav, 
			HttpServletRequest request) {
		System.out.println(request.getSession().getAttribute("CONTACT"));
		mav.setViewName("order/orderInfo");
		return mav;
		
	}

	
	@RequestMapping(value = "/create.html", method = RequestMethod.GET)
	public ModelAndView order(ModelAndView mav, 
			HttpServletRequest request) {
		
		
		Cookie cookie = getCookieByName(request, "MEMBER_ID");
		
		if(cookie == null) {
			return new ModelAndView("redirect:/members/login.html");
		}
		Integer memberId = Integer.parseInt(cookie.getValue());
		cookie = getCookieByName(request, "MEMBER_MOBILE");
		String memberMobile = cookie.getValue();
		
		TaskDO taskDO = (TaskDO) request.getSession().getAttribute("TASK_INFO");
		
		ContactDO contactDO = (ContactDO) request.getSession().getAttribute("CONTACT");
		
		if(taskDO == null) {
			return new ModelAndView("redirect:/index.html");
		}
		
		if(contactDO == null) {
			return new ModelAndView("redirect:/index.html");
		}
	
		
		OrderDO orderDO = new OrderDO();
		OrderDetailDO orderDetailDO = new OrderDetailDO();
		orderDetailDO.setwOCity("重庆");
		orderDetailDO.setwODistrict(contactDO.getwCDistrict());
		orderDetailDO.setwOAddress(contactDO.getwCAddress());
		orderDetailDO.setwOContact(contactDO.getwCContact());
		orderDetailDO.setwOTelephone(contactDO.getwCTelephone());
		orderDetailDO.setwODistrict(contactDO.getwCDistrict());
		switch(taskDO.getServiceType()) {
		case 0: {
			
			orderDO.setwOServiceName(taskDO.getServiceName());
			orderDO.setwOServiceType(taskDO.getServiceType());
			orderDetailDO.setwOServerTime(taskDO.getHours());
			orderDetailDO.setwOStaffCount(taskDO.getStaffCount());
			orderDetailDO.setwOPrice(taskDO.getPrice());
			orderDO.setwOFee(taskDO.getFee());
			orderDetailDO.setwOSubscribe(taskDO.getSubscribe());
			break;
		}
		case 1: {
			orderDO.setwOServiceName(taskDO.getServiceName());
			orderDO.setwOServiceType(taskDO.getServiceType());
			orderDetailDO.setwOServerTime(taskDO.getHours());
			orderDetailDO.setwOLockType(taskDO.getLockType());
			orderDetailDO.setwOPrice(taskDO.getPrice());
			orderDetailDO.setwOMessage(taskDO.getMessage());
			orderDO.setwOFee(taskDO.getFee());
			break;
		}
		case 2: {
			System.out.println(taskDO.getPipType());
			orderDO.setwOServiceName(taskDO.getServiceName());
			orderDO.setwOServiceType(taskDO.getServiceType());
			//orderDetailDO.setwOServerTime(taskDO.getHours());
			orderDetailDO.setwOPipType(taskDO.getPipType());
			if(taskDO.getPipType() == 2) {
				orderDetailDO.setwOToiletType(taskDO.getToiletType());
			}
			
			orderDetailDO.setwOPrice(taskDO.getPrice());
			orderDetailDO.setwOMessage(taskDO.getMessage());
			orderDO.setwOFee(taskDO.getFee());
			break;
		}
		case 3: {
			orderDO.setwOServiceName(taskDO.getServiceName());
			orderDO.setwOServiceType(taskDO.getServiceType());
			orderDetailDO.setwOServerTime(taskDO.getHours());
			orderDetailDO.setwODamageType(taskDO.getDamageType());
			orderDetailDO.setwOPrice(taskDO.getPrice());
			orderDetailDO.setwOMessage(taskDO.getMessage());
			orderDO.setwOFee(taskDO.getFee());
			break;
		}

		case 11: {
			//特殊情况所以为待支付就是待服务
			String date=request.getParameter("wdate");
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm"); 
			
			orderDO.setwOServiceName(taskDO.getServiceName());
			orderDO.setwOServiceType(taskDO.getServiceType());
			orderDetailDO.setwOPrice(taskDO.getPrice());
			orderDetailDO.setwOStaffCount(1);
			orderDO.setStatus(1);//待服务
			
			try {
				//预定时
				orderDetailDO.setwOSubscribe(df.parse(date));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			orderDO.setwOFee(taskDO.getFee());
			break;
		}
		case 12: {
			
			String date=request.getParameter("wdate");
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm"); 
			
			orderDO.setwOServiceName(taskDO.getServiceName());
			orderDO.setwOServiceType(taskDO.getServiceType());
			orderDetailDO.setwOPrice(taskDO.getPrice());
			orderDetailDO.setwOStaffCount(1);
			orderDO.setStatus(1);//待服务
			
			try {
				//预定时间
				orderDetailDO.setwOSubscribe(df.parse(date));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			orderDO.setwOFee(taskDO.getFee());
			break;

		}
		}
		
		MemberCouponDO memberCouponDO = (MemberCouponDO) request.getSession().getAttribute("COUPON_INFO");
		int couponId = 0;
		System.out.println(memberCouponDO);
		if(memberCouponDO != null) {
			System.out.println(memberCouponDO.getId());
			couponId = memberCouponDO.getId();
			orderDO.setwOIsCoupon(1);
			if(memberCouponDO.getwMcCouponType() == 1) {
				orderDO.setwOCoupon(memberCouponDO.getwMcMoney());
			} else {
				float discount = memberCouponDO.getwMcDiscount();
				BigDecimal fee = taskDO.getFee();
				orderDO.setwOCoupon(fee.divide(fee.multiply(new BigDecimal(discount))));
			}
		}
	
		orderDetailDO.setCreateAuthor(memberMobile);

		orderDO.setOrderDetailDO(orderDetailDO);
		orderDO.setwOMembersId(memberId);
		orderDO.setCreateAuthor(memberMobile);
		orderDO.setwOCouponId(couponId);
		ResultDO result = orderService.create(orderDO);
		
		if(!result.isSuccess()) {
			mav.setViewName("error");
			return mav;
		}
		
		int orderID = (int) result.getModel(ResultSupport.FIRST_MODEL_KEY);
	
		//衣橱整理
		if(taskDO.getServiceType()==11){
			request.getSession().setAttribute("couponId", couponId);
			request.getSession().setAttribute("orderID", orderID);
			
			//订单详情页面跳转
			return new ModelAndView("redirect:/order/orderDetail/" + orderID +".html");
		}
		
		return new ModelAndView("redirect:/pay/info/" + orderID + ".html");
	}
	
	@RequestMapping(value = "/payOrder/{id}.html", method = RequestMethod.GET)
	public ModelAndView payOrder(ModelAndView mav, 
			@PathVariable(value="id") Integer id,
			HttpServletRequest request) {
	
	
		Cookie cookie = getCookieByName(request, "MEMBER_ID");
		
		if(cookie == null) {
			return new ModelAndView("redirect:/members/login.html");
		} 
		
		ResultDO resultDO = orderService.get(id);
		OrderDO orderOD = null;
		
		Integer memberId = Integer.parseInt(cookie.getValue());
		if(resultDO.isSuccess()) {
			orderOD = (OrderDO) resultDO.getModel(ResultSupport.FIRST_MODEL_KEY);
			mav.addObject("ORDER_INFO", orderOD);
			resultDO = memberService.get(memberId);
			MembersDO membersDO = (MembersDO) resultDO.getModel(ResultSupport.FIRST_MODEL_KEY);
			List<MemberCouponDO> memberCouponDOList = membersDO.getMemberCoupons();
			
			mav.addObject("MEMBER_COUPON_LIST", memberCouponDOList);
		} else {
			mav.setViewName("error");
		}
		
		mav.setViewName("order/payOrder");
		return mav;
	}
	
	@RequestMapping(value = "/payOrderDetail/{id}.html", method = RequestMethod.GET)
	public ModelAndView payOrderDetail(ModelAndView mav, 
			@PathVariable(value="id") Integer id,
			HttpServletRequest request) {
	
		ResultDO resultDO = orderService.get(id);
		OrderDO orderOD = null;
		if(resultDO.isSuccess()) {
			orderOD = (OrderDO) resultDO.getModel(ResultSupport.FIRST_MODEL_KEY);
			mav.addObject("ORDER_INFO", orderOD);
		} else {
			mav.setViewName("error");
		}
	
		if(resultDO.isSuccess()) {
		
		} else {
			mav.setViewName("error");
		}
		
		mav.setViewName("order/payOrder");
		return mav;
	}
	
	@RequestMapping(value = "/orderDetail/{id}.html", method = RequestMethod.GET)
	public ModelAndView orderDetail(ModelAndView mav, 
			@PathVariable(value="id") Integer id,
			HttpServletRequest request) {
	
		ResultDO resultDO = orderService.get(id);
		OrderDO orderDO = null;
		if(resultDO.isSuccess()) {
			orderDO = (OrderDO) resultDO.getModel(ResultSupport.FIRST_MODEL_KEY);
			System.out.println(orderDO);
			mav.addObject("ORDER_INFO", orderDO);
		} else {
			mav.setViewName("error");
		}
		
		mav.setViewName("order/detail");
		return mav;
	}
	
	@RequestMapping(value = "/paySuccessOrder/{id}.html", method = RequestMethod.GET)
	public ModelAndView paySuccessOrder(ModelAndView mav, 
			@PathVariable(value="id") Integer id,
			HttpServletRequest request) {
	
		ResultDO resultDO = orderService.get(id);
		OrderDO orderOD = null;
		if(resultDO.isSuccess()) {
			orderOD = (OrderDO) resultDO.getModel(ResultSupport.FIRST_MODEL_KEY);
			mav.addObject("ORDER_INFO", orderOD);
		} else {
			mav.setViewName("error");
		}
	
		if(resultDO.isSuccess()) {
		
		} else {
			mav.setViewName("error");
		}
		
		mav.setViewName("order/payOrderDetail");
		return mav;
	}
	
	@RequestMapping(value = "/confirmOrder/{id}.json", method = RequestMethod.GET)
	public ModelAndView confirmOrder(ModelAndView mav, 
			@PathVariable(value="id") Integer id,
			HttpServletRequest request) {
		Cookie cookie = getCookieByName(request, "MEMBER_ID");
		Integer memberId = Integer.parseInt(cookie.getValue());
		cookie = getCookieByName(request, "MEMBER_MOBILE");
		String memberMobile = cookie.getValue();
		OrderDO order = new OrderDO();
		order.setId(id);
		order.setwOMembersId(memberId);
		order.setwOIsConfim(1);
		order.setModifiAuthor(memberMobile);
		order.setStatus(6);
		ResultDO resultDO = orderService.confirm(order);
		if(resultDO.isSuccess()) {
			mav.addObject("JSON_DATA", 1);
		} else {
			mav.addObject("JSON_DATA", 0);
		}
		return mav;
	}
	
	@RequestMapping(value = "/cancel/{id}/{infoId}.json", method = RequestMethod.GET)
	public ModelAndView orderCancel(ModelAndView mav, 
			@PathVariable(value="id") Integer id,
			@PathVariable(value="infoId") Integer infoId,
			HttpServletRequest request) {
		
		String[] caneclInfo = {"时间定错了", "位置定错了", "未准时到达", "暂不需要了", "其他原因"};
		OrderDO orderDO = new OrderDO();
		orderDO.setId(id);
		orderDO.setStatus(4);
		OrderDetailDO orderDetailDO = new OrderDetailDO();
		System.out.println(caneclInfo[infoId]);
		orderDetailDO.setId(id);
		orderDetailDO.setwCaneclInfo(caneclInfo[infoId]);
		String memberMobile = (String) request.getSession().getAttribute("MEMBER_MOBILE");
		orderDO.setModifiAuthor(memberMobile);
		ResultDO resultDO = orderService.modifi(orderDO);
		if(!resultDO.isSuccess()) {
			mav.addObject("JSON_DATA", 0);
		}
		resultDO = orderService.modifiDetail(orderDetailDO);
		if(resultDO.isSuccess()) {
			mav.addObject("JSON_DATA", 1);
		} else {
			mav.addObject("JSON_DATA", 0);
		}
		return mav;
	}
	
	
	
	@RequestMapping(value = "/userOrders/{status}/{pageNo}.html", method = RequestMethod.GET)
	public ModelAndView getUserOrders(ModelAndView mav,
			@PathVariable(value="status") Integer status,
			@PathVariable(value="pageNo") Integer pageNo,
			HttpServletRequest request) {
		Cookie cookie = getCookieByName(request, "MEMBER_ID");	
		if(cookie == null) {
			return new ModelAndView("redirect:/members/login.html");
		} 
		Integer memberId = Integer.parseInt(cookie.getValue());
		OrderQuery query = new OrderQuery();
		if(status != 0) {
			query.setStatus(status);
		}
		query.setMemberId(memberId);
		query.setPage(true);
		query.setPageNO(pageNo);
		query.setPageRows(1000);
		ResultDO result = orderService.list(query);
		if(result.isSuccess()) {
			PageBeanUtil pageBean = new PageBeanUtil();
			long count = (Long) result.getModel(ResultSupport.SECOND_MODEL_KEY);
			pageBean.setCurrentPage(pageNo);
			pageBean.setPageSize(1000);
			pageBean.setRecordCount(count);
			pageBean.setPageCount(count);
			pageBean.setPages(pageNo);
		    mav.addObject("ORDER_LIST", result.getModel(ResultSupport.FIRST_MODEL_KEY));
		    mav.addObject("status", status);
		    mav.setViewName("order/userOrders");
		    
		} else {
			mav.setViewName("error");
		}
		return mav;
	}
	
	
	
	/**
	 * 删除订单
	 * @param mav
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/del/{id}.json", method = RequestMethod.GET)
	public ModelAndView del(ModelAndView mav, 
			@PathVariable(value="id") Integer id,
			HttpServletRequest request) {
		ResultDO result = orderService.remove(id);
		if(result.isSuccess()) {
			mav.addObject("JSON_DATA", 1);
		} else {
			mav.addObject("JSON_DATA", 0);
		}
		return mav;
	}
	
	
	//衣橱计时
		@RequestMapping(value = "/timekeeper.html", method = RequestMethod.GET)
		public ModelAndView timekeeper(ModelAndView mav, 
				HttpServletRequest request) {
			int couponId=(int) request.getSession().getAttribute("couponId");
			int orderID=(int) request.getSession().getAttribute("orderID");
			
			//判断预定时间是否是当天
			ResultDO resultDO = orderService.get(orderID);
			OrderDO orderDO = null;
			
			if(resultDO.isSuccess()) {
				orderDO = (OrderDO) resultDO.getModel(ResultSupport.FIRST_MODEL_KEY);
			}else{
				mav.setViewName("error");
				return mav;
			}
			
			//预定时间
			Date date=orderDO.getwAssigendTime();
			if(date!=null){
				Date d=new Date();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				String date1=sdf.format(date);
				String date2=sdf.format(d);
				
				System.out.println(date1+"    *****   "+date2+"    "+date1.equals(date2));
				
				//判断预定时间是当天
				if(date1.equals(date2)){
					
					Date start=orderDO.getOrderDetailDO().getwOStartTime();
					if(start!=null){
						SimpleDateFormat df = new SimpleDateFormat("HH:mm");
						mav.addObject("startTime", df.format(start));
						mav.addObject("flag", 1);
					}else{
						mav.addObject("flag", 0);
					}
					System.out.println(start);
				
					//计费页面
					mav.addObject("orderID", orderID);
					mav.addObject("couponId", couponId);
					mav.setViewName("goods/timekeeper");
					return mav;
				}else{
					//订单详情页面跳转
					return new ModelAndView("redirect:/order/detail/" + orderID +".html");
				}
			}
			
			return mav;
			
			
		}
		
		//开始服务计时
		@RequestMapping(value = "/wardrobeStartDate.json", method = RequestMethod.GET)
		public ModelAndView wardrobeStartDate(ModelAndView mav, 
				HttpServletRequest request)   {
			//订单id
			String id=request.getParameter("id");
			
			ResultDO resultDO = orderService.get(Integer.parseInt(id));
			OrderDO orderDO = null;
			
			if(resultDO.isSuccess()) {
				orderDO = (OrderDO) resultDO.getModel(ResultSupport.FIRST_MODEL_KEY);
			}else{
				mav.setViewName("error");
				return mav;
			}
			
			//判断开始服务时间是否为空
			if(orderDO.getOrderDetailDO().getwOStartTime()==null){
				//保存明细开始时间
				OrderDetailDO detail=orderDO.getOrderDetailDO();
				Date date=new Date();//开始服务时间

				detail.setwOStartTime(date);//开始服务时间
				orderDO.setOrderDetailDO(detail);
				ResultDO resultDO2 = orderService.modifi(orderDO);
				System.out.println(date+"     "+orderDO.getOrderDetailDO().getwOStartTime()+"      "+resultDO2);
				if(resultDO2.isSuccess()) {
					mav.addObject("JSON_DATA", 1);
				} else {
					mav.addObject("JSON_DATA", 0);
				}
			}
			
			return mav;
		}
		
		//结束并计算
		@RequestMapping(value = "/wardrobePay.html")
		public ModelAndView wardrobePay(ModelAndView mav, 
				HttpServletRequest request) throws ParseException {
			String orderID=request.getParameter("id");//订单id
			String couponId=request.getParameter("couponId");
			
			ResultDO resultDO = orderService.get(Integer.parseInt(orderID));
			OrderDO orderDO = null;
			
			if(resultDO.isSuccess()) {
				orderDO = (OrderDO) resultDO.getModel(ResultSupport.FIRST_MODEL_KEY);
			}else{
				mav.setViewName("error");
				return mav;
			}
			
			Date ends=new Date();//结束时间
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			long endDate = sdf.parse(sdf.format(ends)).getTime();
			long startDate=sdf.parse(sdf.format(orderDO.getOrderDetailDO().getwOStartTime())).getTime();
		    long betweenDate = (endDate - startDate) / (1000 * 60 ); //计算间隔多少分钟数
		    //费用
		    BigDecimal fei=new BigDecimal(betweenDate*2);// 120/60=2
		    System.out.println(betweenDate+"******************"+fei);
		    
		    OrderDetailDO detail=orderDO.getOrderDetailDO();
		    detail.setwOEndTime(ends);
		    detail.setwOServerTime((int)betweenDate);
			orderDO.setwOFee(fei);
			orderDO.setStatus(1); //待付款
			orderDO.setOrderDetailDO(detail);
			
			ResultDO resultDO2 = orderService.modifi(orderDO);
			if(resultDO2.isSuccess()) {
				//mav.addObject(1);
			}
		    
		    return new ModelAndView("redirect:/pay/info/" + orderID + "/" + couponId + ".html");
		}

	
}
